package com.eims.main.livescores.fragment;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.AuthorStringRequest;
import com.android.volley.toolbox.MySingleton;
import com.android.volley.toolbox.StringRequest;
import com.contans.view.BifenGetBaskBallTeamVo;
import com.contans.view.LqFreshVo;
import com.contans.view.getINdexBaskballdayVo;
import com.contans.view.getINdexFootballdayVo;
import com.eims.sls_app.utils.App;
import com.eims.sls_app.utils.LotteryUtils;
import com.eims.sls_app.utils.NetWork;
import com.eims.sls_app.utils.UnicodeUtil;
import com.eims.sls_app.view.MyToast;
import com.eims.sls_app.view.PullToRefreshView;
import com.eims.sls_app.view.PullToRefreshView.OnHeaderRefreshListener;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.ExpandableListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.ExpandableListView.OnGroupClickListener;
import bls.juejin.cn.R;
import progressBar.ProgressDialogBar;

public class MainLqBifenFragment extends Fragment implements OnHeaderRefreshListener {
	private Activity activity;

	private String dataTime;
	private PullToRefreshView mPullToRefreshView;

	private List<getINdexBaskballdayVo> maplist;
	private ArrayList<BifenGetBaskBallTeamVo> arrayList;
	// View
	private ExpandableListView expandableListView;
	private MyHandler myHandler;

	private MyBaskExpandableListView adapter;
	private int reshId = 0;

	private int getRealId = 0;
	private boolean isFresh;

	private List<LqFreshVo> freshVos;

	private boolean isdataFresh;




	public MainLqBifenFragment() {
		super();
	}

	public static MainLqBifenFragment newInstance(boolean isFresh) {

		Bundle args = new Bundle();

		MainLqBifenFragment fragment = new MainLqBifenFragment();
		args.putBoolean("isFresh",isFresh);
		fragment.setArguments(args);
		return fragment;
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_lq_bifen, container, false);
		activity = getActivity();

		Bundle bundle=getArguments();
		if (bundle!=null){
			this.isFresh=bundle.getBoolean("isFresh");
		}


		myHandler = new MyHandler();
		adapter = new MyBaskExpandableListView(activity, maplist);
		init(view);

		return view;
	}

	private void init(View view) {

		expandableListView = (ExpandableListView) view.findViewById(R.id.expandableListView);
		mPullToRefreshView = (PullToRefreshView) view.findViewById(R.id.mPullToRefreshView);

		mPullToRefreshView.setOnHeaderRefreshListener(this);

		ProgressDialogBar.show(activity, dataTime, false);

		expandableListView.setOnGroupClickListener(new OnGroupClickListener() {

			@Override
			public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) {
				// TODO Auto-generated method stub
				return true;
			}
		});
		;
		expandableListView.setOnScrollListener(new OnScrollListener() {

			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
				// TODO Auto-generated method stub

				reshId = firstVisibleItem;

			}
		});
	}

	public void getSaomaXplay() {
		
		getRealId = reshId;
		MySingleton mySingleton = MySingleton.getInstance(activity);
		Log.e("------", "http://nlive.159cai.com/live/basketball/matchlist?type=jc&issue=" + LotteryUtils.getStringDateShort());
		AuthorStringRequest jsonObjectRequest = new AuthorStringRequest(Request.Method.GET,
				"http://nlive.159cai.com/live/basketball/matchlist?type=jc&issue=" + LotteryUtils.getStringDateShort(),
				// "http://nlive.159cai.com/live/basketball/matchlist?type=jc&issue=2018-01-08",
				new Response.Listener<String>() {
					@Override
					public void onResponse(String tn) {

						String getToJson = UnicodeUtil.decodeUnicode(tn);

						Log.e("RealTime", "request--------success------" + getToJson);
						maplist = new ArrayList<getINdexBaskballdayVo>();
						try {

							if (!"".equals(tn) && null != tn) {
								JSONObject item = new JSONObject(getToJson);
								if ("success".equals(item.optString("msg"))) {
									String data = item.optString("data");

									if (!data.equals("")) {
										JSONObject mapJSON = new JSONObject(data);

										// 动态获取key值
										Iterator<String> iterator = mapJSON.keys();
										while (iterator.hasNext()) {
											String key = iterator.next();
											String keyStr = mapJSON.getString(key);
											getINdexBaskballdayVo footballdayVo = new getINdexBaskballdayVo();
											if (keyStr != null && !"[]".equals(keyStr)) {
												arrayList = new ArrayList<BifenGetBaskBallTeamVo>();

												JSONArray team_key = new JSONArray(keyStr);
												BifenGetBaskBallTeamVo ballTeamVo;
												for (int i = 0; i < team_key.length(); i++) {
													JSONObject keyJSON = team_key.getJSONObject(i);
													ballTeamVo = new BifenGetBaskBallTeamVo();
													ballTeamVo.exflag = keyJSON.getString("exflag");

													ballTeamVo.htid = keyJSON.getString("htid");
													ballTeamVo.color = keyJSON.getString("color");
													ballTeamVo.h3 = keyJSON.getString("h3");
													ballTeamVo.h1 = keyJSON.getString("h1");
													ballTeamVo.h4 = keyJSON.getString("h4");
													ballTeamVo.h5 = keyJSON.getString("h5");

													ballTeamVo.mtime = keyJSON.getString("mtime");
													ballTeamVo.lid = keyJSON.getString("lid");
													ballTeamVo.xid = keyJSON.getString("xid");
													ballTeamVo.totaldiff = keyJSON.getString("totaldiff");
													ballTeamVo.mid = keyJSON.getString("mid");
													ballTeamVo.h2 = keyJSON.getString("h2");

													ballTeamVo.state = keyJSON.getString("state");
													ballTeamVo.ascore = keyJSON.getString("ascore");
													ballTeamVo.sid = keyJSON.getString("sid");
													ballTeamVo.totalscore = keyJSON.getString("totalscore");
													ballTeamVo.type = keyJSON.getString("type");

													ballTeamVo.asx = keyJSON.getString("asx");
													ballTeamVo.letscore = keyJSON.getString("letscore");
													ballTeamVo.a1 = keyJSON.getString("a1");
													ballTeamVo.a3 = keyJSON.getString("a3");
													ballTeamVo.a2 = keyJSON.getString("a2");

													ballTeamVo.a5 = keyJSON.getString("a5");
													ballTeamVo.hteam = keyJSON.getString("hteam");
													ballTeamVo.atid = keyJSON.getString("atid");
													ballTeamVo.hsx = keyJSON.getString("hsx");
													ballTeamVo.league = keyJSON.getString("league");

													ballTeamVo.arank = keyJSON.getString("arank");
													ballTeamVo.ateam = keyJSON.getString("ateam");
													ballTeamVo.hscore = keyJSON.getString("hscore");
													ballTeamVo.a4 = keyJSON.getString("a4");

													ballTeamVo.hrank = keyJSON.getString("hrank");
													ballTeamVo.stime = keyJSON.getString("stime");

													arrayList.add(ballTeamVo);
												}

											}

											footballdayVo.setTime(key);
											footballdayVo.setBallarrayList(arrayList);
											maplist.add(footballdayVo);
										}
										myHandler.sendEmptyMessage(1);

									}

									Log.e("-----", maplist.toString());

								} else {
									ProgressDialogBar.stopProgress();
									MyToast.getToast(activity, item.optString("msg")).show();
								}

							}

						} catch (JSONException e) {
							// TODO Auto-generated catch block
							ProgressDialogBar.stopProgress();
							e.printStackTrace();
						}

					}
				}, new Response.ErrorListener() {

					@Override
					public void onErrorResponse(VolleyError error) {
						Log.i("RealTime", "request--------success------" + error);
						ProgressDialogBar.stopProgress();
						MyToast.getToast(activity, "获取失败").show();
					}
				}) {
			@Override
			protected Map<String, String> getParams() throws AuthFailureError {

				Map<String, String> params = new HashMap<String, String>();
				// params.put("appid", "0af5281058488ec1784e433f69d45d81");
				// params.put("custNo", "gl00014156");
				// params.put("orderId", attach);

				return params;
			}
		};

		jsonObjectRequest.setShouldCache(false);// 是否设置缓存

		mySingleton.addToRequestQueue(jsonObjectRequest);

	}

	@Override
	public void onHeaderRefresh(PullToRefreshView view) {
		mPullToRefreshView.postDelayed(new Runnable() {
			@Override
			public void run() {
				if (NetWork.isConnect(activity)) {
					myHandler.removeMessages(3);
					myHandler.removeMessages(4);
					getSaomaXplay();
					// loadInfoview();

				} else {
					MyToast.getToast(activity, "网络连接异常，请检查网络").show();

				}
				mPullToRefreshView.onHeaderRefreshComplete();
			}
		}, 1500);
	}

	@Override
	public void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		App.baskballBfPosition = reshId;
		myHandler.removeMessages(4);
		myHandler.removeMessages(3);
	}

	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		getSaomaXplay();

	}

	@SuppressLint("HandlerLeak")
	class MyHandler extends Handler {
		@Override
		public void handleMessage(Message msg) {
			ProgressDialogBar.stopProgress();
			switch (msg.what) {
			case 0:

				break;
			case 1:
				if (maplist != null) {

					adapter.setMaplist(maplist);
					expandableListView.setAdapter(adapter);
					adapter.notifyDataSetChanged();

					expandableListView.setGroupIndicator(null);
					if (isFresh) {
						expandableListView.setSelection(App.baskballBfPosition);
						isFresh = false;
						Log.e("------", App.baskballBfPosition + "");
					} else {
						expandableListView.setSelection(getRealId);
					}
					// 遍历所有group,将所有项设置成默认展开
					int groupCount = expandableListView.getCount();
					for (int i = 0; i < groupCount; i++) {
						expandableListView.expandGroup(i);
					}

					myHandler.removeMessages(4);
					;
					getFresh();
					myHandler.sendEmptyMessageDelayed(3,900000);
				}

				break;
			case -2:

				break;
			case -1:

				break;
			case 3:
				myHandler.removeMessages(3);
				getSaomaXplay();
				break;
			case 4:
				getRealId = reshId;
				isdataFresh = false;
				if (maplist != null) {
					if (maplist.size() > 0) {
						if (freshVos != null) {
							if (freshVos.size() > 0) {
								for (int i = 0; i < maplist.size(); i++) {
									for (int j = 0; j < maplist.get(i).getBallarrayList().size(); j++) {
										for (int j2 = 0; j2 < freshVos.size(); j2++) {
											if (maplist.get(i).getBallarrayList().get(j).getMid()
													.equals(freshVos.get(j2).getId())) {

												isdataFresh = true;
												maplist.get(i).getBallarrayList().get(j)
														.setLtime(freshVos.get(j2).getLtime());
												maplist.get(i).getBallarrayList().get(j)
														.setLtime(freshVos.get(j2).getLtime());
												int ho1 = Integer.parseInt(freshVos.get(j2).getHo1());
												int ho2 = Integer.parseInt(freshVos.get(j2).getHo2());
												int ho3 = Integer.parseInt(freshVos.get(j2).getHo3());
												int ho4 = Integer.parseInt(freshVos.get(j2).getHo4());
												int hot = Integer.parseInt(freshVos.get(j2).getHot());

												int mainTotal = ho1 + ho2 + ho3 + ho4 + hot;
												int ao1 = Integer.parseInt(freshVos.get(j2).getAo1());
												int ao2 = Integer.parseInt(freshVos.get(j2).getAo2());
												int ao3 = Integer.parseInt(freshVos.get(j2).getAo3());
												int ao4 = Integer.parseInt(freshVos.get(j2).getAo4());
												int aot = Integer.parseInt(freshVos.get(j2).getAot());

												int guesTotal = ao1 + ao2 + ao3 + ao4 + aot;

												maplist.get(i).getBallarrayList().get(j).setH1(ho1 + "");
												maplist.get(i).getBallarrayList().get(j).setH2(ho2 + "");
												maplist.get(i).getBallarrayList().get(j).setH3(ho3 + "");
												maplist.get(i).getBallarrayList().get(j).setH4(ho4 + "");
												maplist.get(i).getBallarrayList().get(j).setH5(hot + "");

												maplist.get(i).getBallarrayList().get(j).setHscore(mainTotal + "");

												maplist.get(i).getBallarrayList().get(j).setA1(ao1 + "");
												maplist.get(i).getBallarrayList().get(j).setA2(ao2 + "");
												maplist.get(i).getBallarrayList().get(j).setA3(ao3 + "");
												maplist.get(i).getBallarrayList().get(j).setA4(ao4 + "");
												maplist.get(i).getBallarrayList().get(j).setA5(aot + "");

												maplist.get(i).getBallarrayList().get(j).setAscore(guesTotal + "");
												maplist.get(i).getBallarrayList().get(j)
														.setState(freshVos.get(j2).getS());

											}
										}
									}
								}
								if (isdataFresh) {
									adapter.setMaplist(maplist);
									expandableListView.setAdapter(adapter);
									adapter.notifyDataSetChanged();

									expandableListView.setGroupIndicator(null);

									expandableListView.setSelection(getRealId);

									// 遍历所有group,将所有项设置成默认展开
									int groupCount = expandableListView.getCount();
									for (int i = 0; i < groupCount; i++) {
										expandableListView.expandGroup(i);
									}

								}

							}
						}
					}
				}
				getFresh();

				break;
			default:
				break;
			}
			super.handleMessage(msg);
		}
	}

	public void getFresh() {
		getRealId = reshId;
		MySingleton mySingleton = MySingleton.getInstance(activity);

		AuthorStringRequest jsonObjectRequest = new AuthorStringRequest(Request.Method.GET,
				"http://nlive.159cai.com/mcache/lqlivecg.html",
				// "http://nlive.159cai.com/live/basketball/matchlist?type=jc&issue=2018-01-08",
				new Response.Listener<String>() {
					@Override
					public void onResponse(String tn) {

						String getToJson = UnicodeUtil.decodeUnicode(tn);

//						Log.e("RealTime", "request--------success------" + getToJson);
						freshVos = new ArrayList<LqFreshVo>();
						try {
							if (!"".equals(tn) && null != tn) {
								JSONObject item = new JSONObject(getToJson);
								if (!"[]".equals(item.optString("e"))) {
									String data = item.optString("e");
									JSONArray team_key = new JSONArray(data);

									LqFreshVo freshVo;
									for (int i = 0; i < team_key.length(); i++) {
										JSONObject keyJSON = team_key.getJSONObject(i);
										freshVo = new LqFreshVo();
										freshVo.rem = keyJSON.getString("rem");
										freshVo.id = keyJSON.getString("id");
										freshVo.hsc = keyJSON.getString("hsc");
										freshVo.ao3 = keyJSON.getString("ao3");

										freshVo.hot = keyJSON.getString("hot");
										freshVo.tsc = keyJSON.getString("tsc");
										freshVo.tp = keyJSON.getString("tp");
										freshVo.ltime = keyJSON.getString("ltime");
										freshVo.tf = keyJSON.getString("tf");

										freshVo.hf = keyJSON.getString("hf");
										freshVo.abc = keyJSON.getString("abc");
										freshVo.aot = keyJSON.getString("aot");
										freshVo.s = keyJSON.getString("s");
										freshVo.ao4 = keyJSON.getString("ao4");

										freshVo.ho4 = keyJSON.getString("ho4");
										freshVo.ao2 = keyJSON.getString("ao2");
										freshVo.ho2 = keyJSON.getString("ho2");
										freshVo.hbc = keyJSON.getString("hbc");
										freshVo.ao1 = keyJSON.getString("ao1");
										freshVo.ho3 = keyJSON.getString("ho3");
										freshVo.ho1 = keyJSON.getString("ho1");
										freshVos.add(freshVo);
									}

//									Log.e("-----", freshVos.toString()); 

									myHandler.sendEmptyMessageDelayed(4, 1000);

								}
							}

						} catch (JSONException e) {
							// TODO Auto-generated catch block
							ProgressDialogBar.stopProgress();
							myHandler.sendEmptyMessageDelayed(4, 1000);
							e.printStackTrace();
						}

					}
				}, new Response.ErrorListener() {

					@Override
					public void onErrorResponse(VolleyError error) {
						Log.i("RealTime", "request--------success------" + error);
						ProgressDialogBar.stopProgress();
						myHandler.sendEmptyMessageDelayed(4, 1000);
						MyToast.getToast(activity, "获取失败").show();
					}
				}) {
			@Override
			protected Map<String, String> getParams() throws AuthFailureError {

				Map<String, String> params = new HashMap<String, String>();
				// params.put("appid", "0af5281058488ec1784e433f69d45d81");
				// params.put("custNo", "gl00014156");
				// params.put("orderId", attach);

				return params;
			}
		};

		jsonObjectRequest.setShouldCache(false);// 是否设置缓存

		mySingleton.addToRequestQueue(jsonObjectRequest);

	}
}
